package org.bonorsoft.modules.wechat.controller;


import org.bonorsoft.common.api.vo.Result;
import org.bonorsoft.common.core.req.model.message.TemplateData;
import org.bonorsoft.common.core.req.model.message.TemplateMessageSendResult;
import org.bonorsoft.common.util.HttpRequest;
import org.bonorsoft.common.util.IPUtils;
import org.bonorsoft.common.util.WxTokenAPI;
import org.bonorsoft.modules.api.wxsendmsg.JwSendTemplateMsgAPI;
import org.bonorsoft.modules.wechat.entity.MyConfig;
import org.bonorsoft.modules.wechat.wxpay.sdk.WXPay;
import org.bonorsoft.modules.wechat.wxpay.sdk.WXPayUtil;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping(value = "/wechat")
public class WeChatController {

    @GetMapping(value = "/config")
    public Map<String, String> getConfig(HttpServletRequest request) throws Exception {
        Map<String, String> config = WxTokenAPI.getConfig(request);
        return config;
    }

    //微信公众号-支付预下单
    @GetMapping(value = "/getinfo")
    public  Map<String, String> wxPay(HttpServletRequest request) throws Exception{
        String openid = request.getParameter("openid");
        MyConfig config = new MyConfig();
        WXPay wxpay = new WXPay(config);
        String ip = IPUtils.getIpAddr(request);

        long time = new Date().getTime();
        SimpleDateFormat yyyyMMdd = new SimpleDateFormat("yyyyMMdd");
        String fm = yyyyMMdd.format(new Date());
        String no = fm + time;

        Map<String, String> data = new HashMap<String, String>();
        data.put("body", "山东博诺有限公司");
        data.put("out_trade_no", no);
        data.put("fee_type", "CNY");
        data.put("total_fee", "1");
        data.put("spbill_create_ip", ip);
        data.put("notify_url", "https://www.williamsunshine.club/wechat/notify");
        data.put("trade_type", "JSAPI");  // 此处指定为扫码支付
        data.put("openid", openid);//of-Oq5bKPR6D7D_eMcdRvu1Ax-nc

        Map<String, String> resp = new HashMap<>();
        try {
            Map<String, String> map = wxpay.unifiedOrder(data);
            String nonce_str = WXPayUtil.generateNonceStr();
            String packages = "prepay_id=" + map.get("prepay_id");
            resp.put("appId", config.getAppID());
            resp.put("timeStamp", WXPayUtil.getCurrentTimestamp()+"");
            resp.put("nonceStr", nonce_str);
            resp.put("package", packages);
            resp.put("signType", "MD5");
            String paySign = WXPayUtil.generateSignature(resp, config.getKey());
            resp.put("paySign", paySign);
            System.out.println(resp);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return resp;
    }

    /**
     * @Title: callBack
     * @Description: 支付完成的回调函数
     * @param:
     * @return:
     */
    @RequestMapping("/notify")
    public String callBack(HttpServletRequest request, HttpServletResponse response) {
        // System.out.println("微信支付成功,微信发送的callback信息,请注意修改订单信息");
        InputStream is = null;
        try {

            is = request.getInputStream();// 获取请求的流信息(这里是微信发的xml格式所有只能使用流来读)
            String xml = WXPayUtil.inputStream2String(is);
            Map<String, String> notifyMap = WXPayUtil.xmlToMap(xml);// 将微信发的xml转map

            System.out.println("微信返回给回调函数的信息为：" + xml);

            if (notifyMap.get("result_code").equals("SUCCESS")) {
                String openid = notifyMap.get("openid");//用户id
                String ordersSn = notifyMap.get("out_trade_no");// 商户订单号
                String amountpaid = notifyMap.get("total_fee");// 实际支付的订单金额:单位 分
                BigDecimal amountPay = (new BigDecimal(amountpaid).divide(new BigDecimal("100"))).setScale(2);// 将分转换成元-实际支付金额:元
                /*
                 * 以下是自己的业务处理------仅做参考 更新order对应字段/已支付金额/状态码
                 */
                String accessToken = WxTokenAPI.getAccessToken();

                TemplateMessageSendResult info = new TemplateMessageSendResult();
                info.setTouser(openid);
                Map<String, TemplateData> data = new HashMap<>();
                TemplateData first = new TemplateData();
                first.setValue("您已成功通过微信支付"+ amountPay +"元。");
                first.setColor("#173177");
                TemplateData DateTime = new TemplateData();
                Date date = new Date();
                DateTime.setValue(date.toString());
                DateTime.setColor("#173177");
                TemplateData PayAmount = new TemplateData();
                PayAmount.setValue(amountPay + "元");
                PayAmount.setColor("#173177");
                TemplateData Location = new TemplateData();
                Location.setValue("山东东营");
                Location.setColor("#173177");
                TemplateData remark = new TemplateData();
                remark.setValue("订单号："+ ordersSn +"，本次交易可能非您本人操作，请尽快核实账号安全。");
                remark.setColor("#173177");
                data.put("first",first);
                data.put("DateTime",DateTime);
                data.put("PayAmount",PayAmount);
                data.put("Location",Location);
                data.put("remark",remark);
                info.setData(data);
                info.setTemplate_id("i8zoFalSBIHC7PBTQRPo9FsBJu7G0k1_2z2jf_XL-Uk");
                info.setUrl("http://www.williamsunshine.club");

                JwSendTemplateMsgAPI.sendTemplateMsg(accessToken,info);
                System.out.println("===notify===回调方法已经被调！！！");

            }

            // 告诉微信服务器收到信息了，不要在调用回调action了========这里很重要回复微信服务器信息用流发送一个xml即可
            response.getWriter().write("<xml><return_code><![CDATA[SUCCESS]]></return_code></xml>");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        return null;
    }

    //微信小程序-支付预下单
    @PostMapping(value = "/orders")
    public Result<?> orders(HttpServletRequest request) throws Exception {
        String openId = "";//用户openid
        String no = new SimpleDateFormat("yyyyMMdd").format(new Date()) + new Date().getTime();
        // 拼接统一下单地址参数
        Map<String, String> paraMap = new HashMap<String, String>();
        // 获取请求ip地址
        String ip = IPUtils.getIpAddr(request);
        MyConfig config = new MyConfig();
        paraMap.put("appid", config.getAppID()); // 商家平台ID
        paraMap.put("body", "智慧教学"); // 商家名称-销售商品类目、String(128)
        paraMap.put("mch_id", config.getMchID()); // 商户ID
        paraMap.put("nonce_str", WXPayUtil.generateNonceStr()); // UUID
        paraMap.put("openid", openId);
        paraMap.put("out_trade_no", no);// 订单号,每次都不同
        paraMap.put("spbill_create_ip", ip);
        paraMap.put("total_fee", "1"); // 支付金额，单位分
        paraMap.put("trade_type", "JSAPI"); // 支付类型
        paraMap.put("notify_url", "https://pay.cht.com.cn/wxpay/notify");// 此路径是微信服务器调用支付结果通知路径随意写
        String sign = WXPayUtil.generateSignature(paraMap, config.getKey());
        paraMap.put("sign", sign);
        try {
            String xml = WXPayUtil.mapToXml(paraMap);// 将所有参数(map)转xml格式
            // 统一下单 https://api.mch.weixin.qq.com/pay/unifiedorder
            String unifiedorder_url = "https://api.mch.weixin.qq.com/pay/unifiedorder";
            System.out.println("xml为：" + xml);
            // String xmlStr = HttpRequest.sendPost(unifiedorder_url,
            // xml);//发送post请求"统一下单接口"返回预支付id:prepay_id
            String xmlStr = HttpRequest.httpsRequest(unifiedorder_url, "POST", xml);
            System.out.println("xmlStr为：" + xmlStr);
            // 以下内容是返回前端页面的json数据
            String prepay_id = "";// 预支付id
            if (xmlStr.indexOf("SUCCESS") != -1) {
                Map<String, String> map = WXPayUtil.xmlToMap(xmlStr);
                prepay_id = map.get("prepay_id");
            }
            Map<String, String> payMap = new HashMap<String, String>();
            payMap.put("appId", config.getAppID());
            payMap.put("timeStamp", WXPayUtil.getCurrentTimestamp() + "");
            payMap.put("nonceStr", WXPayUtil.generateNonceStr());
            payMap.put("signType", "MD5");
            payMap.put("package", "prepay_id=" + prepay_id);
            String paySign = WXPayUtil.generateSignature(payMap, config.getKey());
            payMap.put("paySign", paySign);
            payMap.put("openid", openId);
            payMap.put("outTradeNo", no);
            //将这个6个参数传给前端
            return Result.ok(payMap);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("支付失败！");
        }
    }


}
